﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WeAppsCenter.Core
{
    public delegate void DownloadProgress(int Percentage);
    public delegate void InstallFinished();
    public class Downloader
    {
        public event DownloadProgress Changed;
        public event InstallFinished Finished;
        HttpClient client;
        //WebClient webClient;
        string FileName = "";
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        public async void Download(string url)
        {
            int index = url.LastIndexOf('/');
            FileName = Environment.CurrentDirectory + "\\" + url.Substring(index + 1);
            CancellationToken cancellationToken = tokenSource.Token;
            client = new HttpClient();
            var response = await client.GetAsync(url, cancellationToken);
            Stream stream = await response.Content.ReadAsStreamAsync();
            var n = response.Content.Headers.ContentLength;
            byte[] buffer = new byte[1024];
            var readLength = 0;
            int length;
            FileInfo fileInfo = new FileInfo(FileName);
            using (var fileStream = fileInfo.Create())
            {
                while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                {
                    await fileStream.WriteAsync(buffer, 0, length);
                    readLength += length;
                    long? process = (readLength) / n * 100;
                    Changed((int)process);
                }

            }
            //webClient = new WebClient();
            //webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
            //webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
            //webClient.DownloadFileAsync(new Uri(url), FileName);
            Install(FileName);
            Finished();
        }

        //private void WebClient_DownloadFileCompleted(object? sender, System.ComponentModel.AsyncCompletedEventArgs e)
        //{
        //    Install(FileName);
        //    Finished();
        //}
        public void DownloadWindow_OnProcessCancel()
        {
            tokenSource.Cancel();
        }

        //private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        //{
        //    Changed(e.ProgressPercentage);
        //}
        private void Install(string filename)
        {
            //执行安装
            Process process = new Process();
            process.StartInfo.FileName = filename;
            process.StartInfo.UseShellExecute = true;
            process.Start();
            process.WaitForExit();
            //删除临时文件
            Delete(filename);
        }
        private static void Delete(string filename)
        {
            while (true)
            {
                try
                {
                    File.Delete(filename);
                    break;
                }
                catch (Exception)
                {
                }

            }

        }
    }
}
